package mx.kolobok.noteeditor.ui;

import mx.kolobok.noteeditor.ui.keymap.Keymap;

import javax.swing.*;
import javax.swing.plaf.ListUI;
import java.awt.*;

/**
 * User:  Nikita Belenkiy
 * Date: 29.05.11
 * Time: 0:21
 */
public class UIUtils {
    private UIUtils() {
    }

    /**
     * returns an index of an element only is location really belongs to the cell
     * (not the nearest cell like ListUI.locationToIndex returns)
     * @param list
     * @param location
     * @return
     */
    public static int locationToIndex(JList list, Point location) {
        ListUI ui = list.getUI();
        int index = ui.locationToIndex(list, location);
        if (index != -1) {
            Rectangle cellBounds = ui.getCellBounds(list, index, index);
            boolean contains = cellBounds != null && cellBounds.contains(location);
            return contains ? index : -1;
        }
        return -1;
    }


    public static void addAll(JComponent component, int mapType) {
        InputMap inputMapForComponent = Keymap.getInstance().getInputMapForComponent(component.getClass());
        InputMap currentInputMap = component.getInputMap(mapType);
        KeyStroke[] keyStrokes = inputMapForComponent.allKeys();
        for (KeyStroke keyStroke : keyStrokes) {
            Object actionMapKey = inputMapForComponent.get(keyStroke);
            currentInputMap.put(keyStroke, actionMapKey);
        }
    }
}
